import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

axios.defaults.withCredentials = true;
export const $ajax = axios.create({
    headers: {
        'Content-Type': 'application/json,charset=UTF-8'
    },
    withCredentials: true
})

export const apiUrl = process.env.VUE_APP_API_URL
export const uploadImageUrl = process.env.VUE_APP_IMAGE_URL || ""

$ajax.interceptors.response.use((response) => response, (error) => {
    const loginItems = window.sessionStorage.getItem("isLogin");
    if (!loginItems) {
        let message = {
            type: "error",
            message: "系统错误，请稍候再试",
            duration: 1000
        };
        if (error.response && error.response.data) {
            message.message = error.response.data.errorMessage || "系统错误，请稍候再试"

            if (error.response.data.errorCode === 401) {
                window.sessionStorage.setItem("isLogin", "1")
                message.onClose = () => {
                    window.sessionStorage.clear()
                    router.replace({name: "login"});
                }
            }
        }
        ElMessage.error(message);
    }

    return Promise.reject(error)
})